package com.tsfyun.scm.declarechannel.receiver;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.tsfyun.scm.declarechannel.config.NoticeProperties;
import com.tsfyun.scm.declarechannel.config.ProducerRabbitConfig;
import com.tsfyun.scm.declarechannel.dto.DeclareBizSendDTO;
import com.tsfyun.scm.declarechannel.service.ICusConfigService;
import com.tsfyun.scm.declarechannel.service.IDeclareService;
import com.tsfyun.scm.declarechannel.support.dingding.DingTalkNoticeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * 消息监听接收
 */
@Slf4j
@Component
public class MessageReceiver {

    @Value("${tsfyun.tenant}")
    private String tenant;

    @Autowired
    private NoticeProperties noticeProperties;
    @Autowired
    private IDeclareService declareService;
    @Autowired
    private ICusConfigService cusConfigService;

//    @RabbitListener(queues = "#{tenantQueue.name}")
//    public void declareNoticeReceiver(Channel channel,Message message) throws IOException {
//        String messageContent = new String(message.getBody());
//        String msgId = message.getMessageProperties().getCorrelationId();
//        log.info("监听到消息唯一id:【{}】，消息内容：【{}】",msgId,messageContent);
//        try {
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//            log.info("消息id：【{}】，消息内容：【{}】，消息消费成功",msgId,messageContent);
//        } catch (Exception e) {
//            //告知平台
//            DingTalkNoticeUtil.send2DingDingOtherException(tenant,"","报关渠道》MQ消息消费失败",messageContent,e,noticeProperties.getDingdingUrl());
//            //丢弃消息
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
//            log.info("消息id：【{}】，消息内容：【{}】，消息消费失败",msgId,messageContent);
//        }
//    }

    @RabbitListener(queues = ProducerRabbitConfig.DECLARE_RECEIVE,containerFactory = "customContainerFactory")
    public void declareNoticeReceiver(Channel channel,Message message) throws IOException {
        String messageContent = "";
        String msgId = "";
        try {
            messageContent = new String(message.getBody());
            msgId = message.getMessageProperties().getCorrelationId();
            Object sourceObj = message.getMessageProperties().getHeaders().get("source");
            String source = Objects.nonNull(sourceObj) ? StringUtils.trimWhitespace(sourceObj.toString()) : "";
            log.info("监听到消息唯一id:【{}】，消息内容：【{}】，来源：【{}】",msgId,messageContent,source);
            DeclareBizSendDTO dto = JSONObject.parseObject(messageContent, DeclareBizSendDTO.class);
            declareService.receiver(dto);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("消息id：【{}】，消息内容：【{}】，消息消费成功",msgId,messageContent);
        }catch (Exception e) {
            //丢弃消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            //告知平台
            DingTalkNoticeUtil.send2DingDingOtherException(tenant,"","报关渠道》MQ消息消费失败",messageContent,e,noticeProperties.getDingdingUrl());
            log.error(String.format("消息id：【%s】，消息内容：【%s】，消息消费失败，异常堆栈",msgId,messageContent),e);
        }
    }

//    @RabbitListener(queues = "trigger_event")
//    public void triggerEvent(Channel channel,Message message) throws IOException {
//        String messageContent = new String(message.getBody());
//        String msgId = message.getMessageProperties().getCorrelationId();
//        Object sourceObj = message.getMessageProperties().getHeaders().get("source");
//        String source = Objects.nonNull(sourceObj) ? StringUtils.trimWhitespace(sourceObj.toString()) : "";
//        log.info("监听到事件消息ID:【{}】，消息内容：【{}】，来源：【{}】",msgId,messageContent,source);
//        try {
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//            new Thread(()->{
//                cusConfigService.receiver(messageContent);
//            }).start();
//            log.info("事件消息ID：【{}】，消息内容：【{}】，消息消费成功",msgId,messageContent);
//        }catch (Exception e) {
//            //丢弃消息
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
//            log.error(String.format("事件消息ID：【%s】，消息内容：【%s】，消息消费失败，异常堆栈",msgId,messageContent),e);
//        }
//    }

}
